package gupao.concurrency.simpledemo.interceptor;

import gupao.concurrency.simpledemo.simulate.BizContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.stream.Stream;

@Slf4j
public class UserAndLogInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uid = getUidFromCookie(request);
        if(uid != null){
            BizContext.setUid(uid);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BizContext.clean();
    }

    private String getUidFromCookie(HttpServletRequest request){
        Optional<Cookie> cookie = Stream.of(getCookies(request)).filter(c -> COOKIE_CS.equalsIgnoreCase(c.getName())).findFirst();
        return cookie.map(Cookie::getValue).orElse(null);
    }

    public static final String COOKIE_CS = "suid";

    private Cookie[] getCookies(HttpServletRequest request){
        return request.getCookies() == null ? new Cookie[0] : request.getCookies();
    }
}
